package main

import (
	"fmt"
	"io"
	"net"
	"time"
	znet "zinx/Znet"
)

func main() {
	fmt.Printf("client0 start ...\n")
	time.Sleep(1 * time.Second)
	//链接远程服务器
	conn, err := net.Dial("tcp", "127.0.0.1:8999")
	if err != nil {
		fmt.Println("client Dial err: ", err)
		return
	}

	for {
		dp := znet.NewDataPack()
		buf, err := dp.Pack(znet.NewMsgPackage(0, []byte("zinx client test message send")))
		if err != nil {
			fmt.Println()
			return
		}
		if _, err := conn.Write(buf); err != nil {
			fmt.Println("client write err:", err)
			return
		}

		//接收服务器的消息
		binHead := make([]byte, dp.GetHeadLen())
		if _, err := io.ReadFull(conn, binHead); err != nil {
			fmt.Println("read err:", err)
			return
		}

		//读取数据
		msghead, err := dp.UnPack(binHead)
		if err != nil {
			fmt.Println("client err", err)
			return
		}
		if msghead.GetDataLen() > 0 {
			msg := msghead.(*znet.Message)
			msg.Data = make([]byte, msg.GetDataLen())
			if _, err := io.ReadFull(conn, msg.Data); err != nil {
				fmt.Println("read msg data err", err)
				return
			}
			fmt.Println("recv server msg :id=", msg.Id, "len=", msg.DataLen, "data=", string(msg.Data))

		}
		time.Sleep(1 * time.Second)
	}
}
